package com.ethanzzh.ethanzzh_xdclass.controller;


import com.ethanzzh.ethanzzh_xdclass.config.AliyunOSSConfig;
import com.ethanzzh.ethanzzh_xdclass.utils.AliyunOSSUtil;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

@Controller
@RequestMapping("/upload")
public class OssUploadController {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 文件上传
     *
     * @param file
     */

    @RequestMapping(value = "uploadBlog",method = RequestMethod.POST)
    public String uploadBlog(MultipartFile file) {

        logger.info("============>文件上传");
        try {

            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = AliyunOSSUtil.upload(newFile);

                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "index";
    }

    @RequestMapping(value = "toUploadBlog",method = RequestMethod.GET)
    public String toUploadBlog(){
        return "upload";
    }



    /**
     * 获取Object名称列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getObjectList",method = RequestMethod.GET)
    public List<String> getObjectList() {
        String bucketName = AliyunOSSConfig.ALIYUN_BUCKET_NAME;
        List<String> objectList = AliyunOSSUtil.getObjectList(bucketName);
        return objectList;

    }

    /**
     * 删除文件
     */
    @RequestMapping(value = "deleteBlog",method = RequestMethod.GET)
    @ResponseBody
    public String deleteBlog(){
        String ObjectKey = "home/2018-10-21/faba399070e44f8ebc6f94fd217ce577-查课表2.0.xlsx";
        AliyunOSSUtil.deleteBlog(ObjectKey);
        return "删除成功";
    }


}
